package demo.BlockingQueueDemo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by zhangyanfei on 2018/4/12.
 * 生产者 消费者 模式
 * @author zhangyanfei
 * @date 2018/04/12
 */
public class ArrayBlockingQueueDemo {
    /**
     * ArrayBlockingQueue   定长数组 top end    默认非公平锁
     *
     * push 和 poll 共用一个锁 所以不能并行
     *
     * LinkedBlockingQueue  链表组成
     *
     * push 和 poll 不共用一个锁  所以可以并行 但在长期高并发情况下由于会额外的创建node 不推荐使用会出现full gc
     *
     * 如果push的速度远大于 poll 的速度会出现 内存溢出的问题
     */

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<PcData> queue = new LinkedBlockingQueue<>(10);
        // 几个线程往队列里面生成数据  几个线程取出数据
        Producer p1 = new Producer(queue);
        Producer p2 = new Producer(queue);
        Producer p3 = new Producer(queue);
        Consumer c1 = new Consumer(queue);
        Consumer c2 = new Consumer(queue);
        Consumer c3 = new Consumer(queue);

        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(p1);
        service.execute(p2);
        service.execute(p3);
        service.execute(c1);
        service.execute(c2);
        service.execute(c3);
        Thread.sleep(10*1000);
        p1.stop();
        p2.stop();
        p3.stop();
        Thread.sleep(3000);
        service.shutdown();
    }
}
